<?php
/**
 * 
 * @author Youssef Driouach
 *
 */
class Application_Model_PhoneMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Phone');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Phone $phone){
		
		
		$productMapper = new Application_Model_ProductMapper();
		$row = $productMapper->save($phone);
		//TODO set the object save function to return the id of the object saved
		//$where = array('model = ?' => (string)$product->getModel());
		$phone->setProductId($row);
		
		$data = array(
				'id_product' 	=> $phone->getProductId(),
				'type'			=> $phone->getType(),
		);
		
		if (null === ($id = $phone->getphoneId())) {
			unset($data['id_phone']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_phone = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_Phone $phone)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$phone->setPhoneId($row->id_phone);
		$phone->setProductId($row->id_product);
		$phone->setType($row->type);
		
		$productMapper = new Application_Model_ProductMapper();
		$phone = $productMapper->find($phone->getProductId(), $phone);
	
		return $phone;
	}
	
	public function delete($id)
	{
	
		$phone= new Application_Model_Phone();
		$productMapper = new Application_Model_ProductMapper();
		$phone = $this->find($id, new Application_Model_Phone());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_phone = ?' => $id));
		}
	
		$productMapper->delete($phone->getProductId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Phone $phone)
	{
		$productMapper = new Application_Model_ProductMapper();
		$requestBuilder = new Application_Model_Builder_Request();
		$doc->addField(Zend_Search_Lucene_Field::Text('type', $phone->getType(), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'phone', 'utf-8'));
		$doc = $productMapper->indexBuilder($doc, $phone);
	
		return $doc;
	}
	
}